package com.guawazi.fragment;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.utils.ColorTemplate;
import com.guawazi.MainActivity;
import com.guawazi.R;
import com.guawazi.base.BaseFragment;
import com.guawazi.bean.DataEntity;
import com.guawazi.nohttp.HttpListener;
import com.guawazi.utils.DynamicLineChartManager;
import com.guawazi.utils.JsonUtil;
import com.guawazi.utils.SharedPreferenceUtils;
import com.orhanobut.logger.Logger;
import com.yanzhenjie.nohttp.NoHttp;
import com.yanzhenjie.nohttp.RequestMethod;
import com.yanzhenjie.nohttp.rest.Request;
import com.yanzhenjie.nohttp.rest.Response;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

public class MonitorFragment extends BaseFragment {
    @BindView(R.id.chart)
    LineChart mChart;
    @BindView(R.id.btn)
    Button btn;
    @BindView(R.id.flag_img)
    ImageView flagImg;
    @BindView(R.id.isok_img)
    ImageView isokImg;
    @BindView(R.id.flag_tv)
    TextView flagTv;
    Unbinder unbinder;

    private static final int UPDATE_VIEW = 0x01;

    private MainActivity activity;
    private DynamicLineChartManager dynamicLineChartManager;
    private Timer timer;
    private DataEntity entity;
    private boolean status;

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case UPDATE_VIEW:
                    if(flagTv == null || flagImg == null || isokImg == null){
                        return;
                    }
                    if("B".equals(entity.getMarkerPosition())){
                        flagImg.setImageResource(R.drawable.b_icon);
                        isokImg.setImageResource(R.drawable.warn_icon);
                        flagTv.setText("脊背姿态不端正");
                    }else {
                        flagImg.setImageResource(R.drawable.a_icon);
                        isokImg.setImageResource(R.drawable.ok_icon);
                        flagTv.setText("脊背端正姿态");
                    }
                    break;
            }
        }
    };

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        activity = (MainActivity) getActivity();
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_monitor_layout, container, false);
        unbinder = ButterKnife.bind(this, view);

        activity.hideMenu();
        initView();
        return view;
    }

    private void initView() {
        dynamicLineChartManager = new DynamicLineChartManager(mChart, "脊背弯曲度", ColorTemplate.getHoloBlue());
        dynamicLineChartManager.setYAxis(800, 0, 10);
        dynamicLineChartManager.setDescription("时间");
    }

    private void requestData() {
        Request<JSONObject> request = NoHttp.createJsonObjectRequest("http://119.23.48.248:3000/project/getAll", RequestMethod.GET);
        request.add("size", 1);
        request.add("phoneNumber", SharedPreferenceUtils.getValue(activity, "phoneNum", ""));
        activity.request(0x01, request, httpListener, true, false);
    }

    private HttpListener<JSONObject> httpListener = new HttpListener<JSONObject>() {

        @Override
        public void onSucceed(int what, Response<JSONObject> response) {
            if (response.getHeaders().getResponseCode() == 200) {
                switch (what) {
                    case 0x01: {
                        JSONObject object = response.get();
                        Logger.json(object.toString());
                        try {
                            int code = object.getInt("code");
                            if (code == 200) {
                                JSONObject object1 = object.getJSONObject("data");
                                JSONArray summary = object1.getJSONArray("summary");
                                entity = (DataEntity) JsonUtil.stringToObject(summary.get(0).toString(), DataEntity.class);
                                addEntry((int) entity.getVoltageValue());

                                handler.sendEmptyMessage(UPDATE_VIEW);
                            } else {
                                showToast(object.getString("msg"));
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                    break;
                }
            }
        }

        @Override
        public void onFailed(int what, Response<JSONObject> response) {
            activity.showMessageDialog(R.string.request_failed, response.getException().getMessage());
        }
    };

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
        if(timer != null){
            timer.cancel();
        }
        handler.removeCallbacksAndMessages(null);
    }

    //按钮点击添加数据
    public void addEntry(int value) {
        dynamicLineChartManager.addEntry(value);
    }

    @OnClick(R.id.btn)
    public void onViewClicked() {
        if (status == true) {
            status = false;
            timer.cancel();
            btn.setText("开启监控");
        } else {
            status = true;
            timer = new Timer();
            timer.schedule(new TimerTask() {
                @Override
                public void run() {
                    activity.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            requestData();
                        }
                    });
                }
            }, 0, 1000);
            btn.setText("停止监控");
        }
    }
}
